package com.renshine.swing.component.panel;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;

import org.springframework.beans.factory.annotation.Autowired;

import com.renshine.base.dao.QueryDao;
import com.renshine.swing.Layout;
import com.renshine.swing.model.BaseTableModel;

/**
 * 根据表格模型创建表格模板
 * 
 * @author deyang
 *
 */
@SuppressWarnings("serial")
public class TablePanel extends JPanel {
	@Autowired
	QueryDao queryDao;
	
	public static final String TABLE = "tables";

	private BaseTableModel model;
	private JTabbedPane tab = new JTabbedPane(JTabbedPane.TOP);
	private Map<String, JSplitPane> content = new HashMap<String, JSplitPane>();
	private Map<String, BaseTableModel> mapModel = new HashMap<String, BaseTableModel>();

	public TablePanel(BaseTableModel model) {
		// 空布局
		this.setLayout(null);
		//this.setBorder(BorderFactory.createTitledBorder(""));
		// 创建组件
		this.model = model;
		// 组件定位
		Layout.ready().setLocate(tab, 0);
		// 将组件装入面板
		add(tab);
	}
	
	/**
	 * 加载内容并添加监听器
	 * 
	 * @param tbNames 表名
	 */
	public void loadAndAddListener(List<String> tbNames){
		JSplitPane jsplit;
		
		// 1. 判断是否是表格初始化
		if (tbNames == null) {
			jsplit = content.get(TABLE);
			if (jsplit == null) {
				jsplit = model.createJSplit(null);
		    	content.put(TABLE, jsplit);
		    	mapModel.put(TABLE, model);
			}
			tab.addTab(TABLE, jsplit);
			return;
		}
		
		// 2. 字段类型的编辑
		tab.removeAll();
		for (String tbName : tbNames) {
			jsplit = content.get(tbName);
			if (jsplit == null) {
				jsplit = model.createJSplit(tbName);
		    	content.put(tbName, jsplit);
		    	mapModel.put(tbName, (BaseTableModel)((JTable)((JScrollPane)jsplit.getRightComponent()).getViewport().getView()).getModel());
			}
			tab.addTab(tbName, jsplit);
			
		}
	}

	public BaseTableModel getModel() {
		return model;
	}

	public void setModel(BaseTableModel model) {
		this.model = model;
	}

	public JTabbedPane getTab() {
		return tab;
	}

	public void setTab(JTabbedPane tab) {
		this.tab = tab;
	}

	public Map<String, JSplitPane> getContent() {
		return content;
	}

	public void setContent(Map<String, JSplitPane> content) {
		this.content = content;
	}

	public Map<String, BaseTableModel> getMapModel() {
		return mapModel;
	}

	public void setMapModel(Map<String, BaseTableModel> mapModel) {
		this.mapModel = mapModel;
	}

}
